// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  switch (event.action) {
    case 'updatePinLun': {
      return updatePinLun(event)
    }
    case 'updateXinJianStatus': {
      return updateXinJianStatus(event)
    }
    case 'updateBiYouList': {
      return updateBiYouList(event)
    }
    case 'updateHuaTiNumber': {
      return updateHuaTiNumber(event)
    }
    case 'updateHuaTiPinLun': {
      return updateHuaTiPinLun(event)
    }
    case 'updateBiMing': {
      return updateBiMing(event)
    }
    case 'deleteCollectionItem': {
      return deleteCollectionItem(event)
    }
    
    default: {
      return
    }
  }
}

async function updatePinLun(event) {
  try {
    return await db.collection('wenzhangbiao').where({
      _id: event.id
    })
    .update({
      data: {
        pinLun: event.pinLun
      },
    })
  } catch (e) {
    console.error(e)
  }
}

async function updateXinJianStatus(event) {
  try {
    return await db.collection('xinjian').where({
      _id: event.id
    })
    .update({
      data: {
        status: event.status
      },
    })
  } catch (e) {
    console.error(e)
  }
}

async function updateBiYouList(event) {
  try {
    return await db.collection('userInfo').where({
      _openid: event.openid
    })
    .update({
      data: {
        biYouLieBiao: event.biyoudata
      },
    })
  } catch (e) {
    console.error(e)
  }
}


async function updateHuaTiNumber(event) {
  try {
    return await db.collection('huati').where({
      _id: event.id
    })
    .update({
      data: {
        [event.result]: _.inc(1)
      },
    })
  } catch (e) {
    console.error(e)
  }
}

async function updateHuaTiPinLun(event) {
  try {
    return await db.collection('huati').where({
      _id: event.id
    })
    .update({
      data: {
        pinLun: event.pinLun
      },
    })
  } catch (e) {
    console.error(e)
  }
}

async function updateBiMing(event) {
  const {
    OPENID
  } = cloud.getWXContext()
  try {
    return await db.collection('userInfo').where({
      _openid: OPENID
    })
    .update({
      data: {
        biMing: event.biMing
      },
    })
  } catch (e) {
    console.error(e)
  }
}

async function deleteCollectionItem(event) {
  try {
    return await db.collection(event.collection).where({
      _id: event.id
    }).remove()
  } catch (e) {
    console.error(e)
  }
}

